package com.thinkit.bigdata.web.controller.cronTask;

import com.thinkit.bigdata.core.util.DESUtils;
import com.thinkit.bigdata.core.util.FtpUtil;
import com.thinkit.bigdata.web.coremet.SystemStatic;
import com.thinkit.bigdata.web.model.config.SysArea;
import com.thinkit.bigdata.web.model.result.HtmlResult;
import com.thinkit.bigdata.web.service.config.AreaService;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

/**
 * 系统告警通知
 */
@Component
public class SystemAlarmCronTask {

    private static Logger logger = Logger.getLogger(SystemAlarmCronTask.class);

    @Resource
    private AreaService areaService;

    /**
     * 检测FTP链接是否正常任务 2小时执行一次
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void cronLocalAudioDel() {
        String logTxt = "【检测FTP链接是否正常任务】";
        logger.info(logTxt + "启动");
        boolean start = true;
        try {
            start = FtpUtil.sendCcs("cronSystemAlarmTask", logTxt);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!start) {
            logger.info(logTxt + "该方法其他机器有启动");
            return;
        }
        Map<String, Map<String, String>> maps = SystemStatic.FTP_CONFIG_MAP;
        for (Map.Entry<String, Map<String, String>> mapEntry : maps.entrySet()) {
            String code = mapEntry.getKey();
            String host = mapEntry.getValue().get("host");
            String port = mapEntry.getValue().get("port");
            String username = mapEntry.getValue().get("username");
            String password = mapEntry.getValue().get("password");
            String status = mapEntry.getValue().get("status");
            if ("0".equals(status)) {//未启用得不检查
                continue;
            }
            HtmlResult result = FtpUtil.isFtpUtil(
                    host,
                    Integer.parseInt(port),
                    DESUtils.getDecryptString(username),
                    DESUtils.getDecryptString(password)
            );
            SysArea area = areaService.selectByPrimaryCode(code);
            if (result.getCode() == 0) {
                logger.info(logTxt + area.getArea() + "FTP链接正常");
                continue;
            }
            String isSendStr = "【" + area.getArea() + "】FTP链接异常，请检查！";
            // 生成发送post请求的参数
            if (FtpUtil.sendMobileMes("15313095360", isSendStr)) {
                logger.info("短信通知成功");
            }
        }
    }
}